package com.kinon.tyjaccount.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.tyjaccount.Constatus;
import com.kinon.tyjaccount.R;
import com.kinon.tyjaccount.data.UPacketFactory;
import com.kinon.tyjaccount.sqlitebean.Card;
import com.kinon.tyjaccount.sqlitebean.SettletmentBean;
import com.kinon.tyjaccount.tools.HttpTools;
import com.kinon.tyjaccount.tools.MyShowDialog;
import com.kinon.tyjaccount.tools.NetWorkUtil;
import com.kinon.tyjaccount.tools.SysTimeManage;
import com.kinon.tyjaccount.tools.ToastUtil;
import com.kinon.tyjaccount.uitl.SoundPoolManage;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import sunmi.ds.DSKernel;
import sunmi.ds.callback.IConnectionCallback;
import sunmi.ds.callback.IReceiveCallback;
import sunmi.ds.data.DSData;
import sunmi.ds.data.DSFile;
import sunmi.ds.data.DSFiles;
import sunmi.ds.data.DataPacket;

import static com.kinon.tyjaccount.R.id.et_id;

public class JiesuanjineActivity extends Activity {
	
	private TextView tv_jine;
	private TextView tv_fanhui;
	private EditText et_pay;
	String id;
	String token;
	double jine;

	HttpTools httptools=null;

    Handler showHandle=new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_jiesuanjine);
		initRes();
	}

	private void initRes() {
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		token = sp.getString("data", "");
		tv_jine=(TextView)findViewById(R.id.tv_jine);
		et_pay=(EditText)findViewById(R.id.et_pay);
		jine = getIntent().getDoubleExtra("jine",0.00);

//		Log.i("zq", "金额----"+jine);
		tv_jine.setText("￥"+jine);
		et_pay.requestFocus();
		et_pay.addTextChangedListener(watcher);
		tv_fanhui=(TextView)findViewById(R.id.tv_fanhui);
		tv_fanhui.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!Constatus.URGENT_TYPE){
					Cancle();
				}else {
					finish();
				}
			}
		});
		jieShow();
	}

	/**副屏显示*/
	private void jieShow(){
//		DSKernel mDSKernel = DSKernel.newInstance();
		mDSKernel.init(getApplicationContext(), new IConnectionCallback() {
			@Override
			public void onDisConnect() {

			}

			@Override
			public void onConnected(ConnState state) {

			}
		});
		mDSKernel.addReceiveCallback(new IReceiveCallback() {
			@Override
			public void onReceiveData(DSData data) {

			}

			@Override
			public void onReceiveFile(DSFile file) {

			}

			@Override
			public void onReceiveFiles(DSFiles files) {

			}

			@Override
			public void onReceiveCMD(DSData cmd) {

			}
		});
		JSONObject json = new JSONObject();
		try {
			json.put("title", "请支付：");
			json.put("content","￥ "+jine);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		DataPacket packet = UPacketFactory.buildShowText(DSKernel.getDSDPackageName(), json.toString(),null);
		mDSKernel.sendData(packet);
	}
	/**订单支付*/
	private void Dingdan(String str) {
		synchronized(str) {
			et_pay.setText("");
			if (NetWorkUtil.isNetwork(getApplicationContext()) == false) {
				ToastUtil toastUtil = new ToastUtil();
				toastUtil.Short(getApplicationContext(), "  " + "当前网络不可用")
						.setToastBackground(Color.WHITE, 0).show();

				return;
			}

			id = getIntent().getStringExtra("orderid");
//		Toast.makeText(JiesuanjineActivity.this, id, Toast.LENGTH_SHORT).show();
			if (httptools == null) {
				httptools = new HttpTools(JiesuanjineActivity.this);
			}

			String cardId = str.substring(0, str.length());
			httptools.otherPay(token, id, cardId, new JsonDingdan());
		}
	}
	public class JsonDingdan extends JsonHttpResponseHandler {
		@Override
		public void onStart() {
			Log.e("lh","onStart---");
			MyShowDialog.showLoadingDialog(JiesuanjineActivity.this, "订单支付中....");
			super.onStart();
		}

		@Override
		public void onRetry() {
			super.onRetry();
			Log.e("lh","onRetry---");
		}

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			// TODO Auto-generated method stub
			super.onSuccess(statusCode, headers, response);
			MyShowDialog.closeLoadingDialog();
			Log.i("info", "jiesuan---"+response.toString());
			try {
				boolean code = response.getBoolean("code");
				String msg = response.getString("msg");
				if(code==true){
					SoundPoolManage.getInstance(JiesuanjineActivity.this).soundpPlay(1);
					JSONObject data = response.getJSONObject("data");
					String balance = data.getString("balance");
					Toast.makeText(JiesuanjineActivity.this, msg, Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(JiesuanjineActivity.this,PayresultActivity.class);
					intent.putExtra("balance",balance);
					startActivity(intent);
					finish();
				}else{
					SoundPoolManage.getInstance(JiesuanjineActivity.this).soundpPlay(2);
					Toast.makeText(JiesuanjineActivity.this, msg, Toast.LENGTH_SHORT).show();
					int data=response.getInt("data");
					if(data==0){
						et_pay.setText("");
					}else if(data==2){
						showBanlance();
					}

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
		}
		@Override
		public void onFailure(int statusCode, Throwable e, JSONArray errorResponse) {
			super.onFailure(statusCode, e, errorResponse);
			SoundPoolManage.getInstance(JiesuanjineActivity.this).soundpPlay(2);
			MyShowDialog.closeLoadingDialog();
		}

		@Override
		public void onFailure(Throwable e, JSONObject errorResponse) {
			super.onFailure(e, errorResponse);
			SoundPoolManage.getInstance(JiesuanjineActivity.this).soundpPlay(2);
			MyShowDialog.closeLoadingDialog();
			Toast.makeText(JiesuanjineActivity.this, "网络请求失败",
					 Toast.LENGTH_SHORT).show();

		}
	}

	// SDK核心类
	DSKernel mDSKernel = DSKernel.newInstance();

    Runnable mRunnable=new Runnable() {
        @Override
        public void run() {
            jieShow();
        }
    };
	private void showBanlance(){
		JSONObject json = new JSONObject();
		try {
				json.put("title", "支付失败");
				json.put("content","  余额不足");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		//显示文字
		DataPacket packet = UPacketFactory.buildShowText(DSKernel.getDSDPackageName(),
				json.toString(),null);
		mDSKernel.sendData(packet);
        showHandle.postDelayed(mRunnable,1*1000);
	}

	/**取消订单（点击返回按钮时触发）*/
	private void Cancle() {
		if(NetWorkUtil.isNetwork(getApplicationContext())==false)
		{
			ToastUtil toastUtil=new ToastUtil();
			toastUtil.Short(getApplicationContext(),"  "+"当前网络不可用")
					.setToastBackground(Color.WHITE,0).show();
			return;
		}
		id=getIntent().getStringExtra("orderid");
//		Toast.makeText(JiesuanjineActivity.this, id, Toast.LENGTH_SHORT).show();
		if (httptools == null) {
			httptools = new HttpTools(JiesuanjineActivity.this);
		}
//		String str = et_pay.getText().toString();
		httptools.cancelOrder(token, id,new JsonCancle());
	}
	public class JsonCancle extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(int statusCode, Header[] headers,
							  JSONObject response) {
			super.onSuccess(statusCode, headers, response);
		}

		@Override
		public void onFailure(Throwable e, JSONObject errorResponse) {
			super.onFailure(e, errorResponse);
			Toast.makeText(JiesuanjineActivity.this, "网络请求失败",
					Toast.LENGTH_SHORT).show();
		}
	}
    int i=0;

	/**EditText监听*/
    private TextWatcher watcher = new TextWatcher() {
	    
	    @Override
	    public void onTextChanged(CharSequence s, int start, int before, int count) {
	    }
	    
	    @Override
	    public void beforeTextChanged(CharSequence s, int start, int count,
	            int after) {
	    }
	    
	    @Override
	    public synchronized void afterTextChanged(Editable s) {
//	    	Toast.makeText(getActivity(), "4", 1).show();
			if (et_pay.getText().length()==8) {
				String str = et_pay.getText().toString().trim();
				if(!Constatus.URGENT_TYPE){
					Dingdan(str);
				}else{
					addSqlite(str);

				}
			}
	    }
	};

	private void addSqlite(String str){
		synchronized (str) {
			et_pay.setText("");
			int cardnub= DataSupport.where("no = ?",str).count(Card.class);
			if(cardnub<1){
				et_pay.setText("");
				SoundPoolManage.getInstance(JiesuanjineActivity.this).soundpPlay(2);
				Toast.makeText(JiesuanjineActivity.this,"刷卡频率过快或付款码无效",Toast.LENGTH_SHORT).show();
				return;
			}
			long sysTime = System.currentTimeMillis();
			String id = SysTimeManage.getInstage().getOrderId(sysTime);
//			int type = SysTimeManage.getInstage().getOrderType(sysTime);
			String time = SysTimeManage.getInstage().getDateTime(sysTime);
			String date = SysTimeManage.getInstage().getDate(sysTime);
			SettletmentBean settl = new SettletmentBean
					(id, str, 0, jine + "", time, 0, 0, 0, date, 0);
			boolean save = settl.save();
			if (save) {
//				showBanlance();
				Toast.makeText(getApplicationContext(), "刷卡成功", Toast.LENGTH_SHORT).show();
				SoundPoolManage.getInstance(JiesuanjineActivity.this).soundpPlay(1);
				Intent intent = new Intent(JiesuanjineActivity.this, PayresultActivity.class);
				intent.putExtra("type", Constatus.URGENT_CARD_SUCCESS);
				startActivity(intent);
				finish();
			} else {
				SoundPoolManage.getInstance(JiesuanjineActivity.this).soundpPlay(2);
				Toast.makeText(getApplicationContext(), "刷卡失败", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
	       super.onWindowFocusChanged(hasFocus);
	       if (hasFocus) {

	            View decorView = getWindow().getDecorView();
	                 decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE 
	                  | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
	                  | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
	                  |View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 
	                  |View.SYSTEM_UI_FLAG_FULLSCREEN);
	               }
	}

//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if(keyCode==KeyEvent.KEYCODE_BACK){
//			Cancle();
//		}
//		return false;
//	}

	@Override
	public void onBackPressed() {
		Cancle();
		super.onBackPressed();
	}
}
